package io.finer.erp.jeecg.bas.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.finer.erp.jeecg.bas.dto.ZrkShopOrderDTO;
import io.finer.erp.jeecg.bas.entity.*;
import io.finer.erp.jeecg.bas.vo.CreateZzOrderVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.ConstantMall;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.RestUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;

import cn.hutool.core.date.DateUtil;
import io.finer.erp.jeecg.bas.dto.ZrkOrderProductDTO;
import io.finer.erp.jeecg.bas.dto.ZrkShopCustomerDTO;
import io.finer.erp.jeecg.bas.dto.ZrkShopTotalDTO;
import io.finer.erp.jeecg.bas.service.IBasCustomerAddressService;
import io.finer.erp.jeecg.bas.service.IBasCustomerService;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasMeasureUnitService;
import io.finer.erp.jeecg.bas.service.IBasPfMaterialService;
import io.finer.erp.jeecg.bas.service.IBasProductFormulaService;
import io.finer.erp.jeecg.bas.service.IBasSupplierService;
import io.finer.erp.jeecg.bas.service.IZrkOrderProductService;
import io.finer.erp.jeecg.bas.service.IZrkPushSetService;
import io.finer.erp.jeecg.bas.service.IZrkShoporderService;
import io.finer.erp.jeecg.bas.service.IZrkUserCustomerService;
import io.finer.erp.jeecg.bas.service.IZzDeviceTypeService;
import io.finer.erp.jeecg.bas.service.IZzShoporderService;
import io.finer.erp.jeecg.bas.vo.OrderProductVO;
import io.finer.erp.jeecg.bas.vo.OrderVO;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.service.IStkInventoryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillEntryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 商城订单信息表
 * @Author: jeecg-boot
 * @Date:   2020-09-04
 * @Version: V1.0
 */
@Api(tags="商城订单信息表")
@RestController
@RequestMapping("/bas/zrkShoporder")
@Slf4j
public class ZrkShoporderController extends JeecgController<ZrkShoporder, IZrkShoporderService> {

	@Autowired
	private IZrkShoporderService zrkShoporderService;

	@Autowired
	private IZrkOrderProductService zrkOrderProductService;

	@Autowired
	private IBasMaterialService basMaterialService;

	@Autowired
	private IBasCustomerService basCustomerService;

	@Autowired
	private IZrkUserCustomerService zrkUserCustomerService;

	@Autowired
	private IZzShoporderService zzShoporderService;

	@Autowired
	private IStkIoBillService stkIoBillService;

	@Autowired
	private IStkIoBillEntryService stkIoBillEntryService;

	@Autowired
	private IBasCustomerAddressService basCustomerAddressService;

	@Autowired
	private IBasMeasureUnitService basMeasureUnitService;

	@Autowired
	private IBasSupplierService basSupplierService;

	@Autowired
	private IBasProductFormulaService basProductFormulaService;

	@Autowired
	private IBasPfMaterialService basPfMaterialService;

	@Autowired
	private IStkInventoryService stkInventoryService;

	@Autowired
	private IBasMaterialCategoryService basMaterialCategoryService;
	
	@Autowired
	private IZrkPushSetService zrkPushSetService;
	@Autowired
	private IBasPfMaterialService pfMaterialService;
	@Autowired
	private IBasProductFormulaService productFormulaService;
	@Autowired
	private ISysBaseAPI iSysBaseAPI;
	@Autowired
	private IZzDeviceTypeService deviceTypeService;
	
	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * @param zrkShoporder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "商城订单信息表-分页列表查询")
	@ApiOperation(value="商城订单信息表-分页列表查询", notes="商城订单信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ZrkShoporder zrkShoporder,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		Page<ZrkShopOrderDTO> page = new Page<ZrkShopOrderDTO>(pageNo, pageSize);
		IPage<ZrkShopOrderDTO> pageList = zrkShoporderService.listByModel(page, zrkShoporder);
		return Result.ok(pageList);
	}

	/**
	 *   添加
	 * @param zrkShoporder
	 * @return
	 */
	@AutoLog(value = "商城订单信息表-添加")
	@ApiOperation("商城订单信息表-添加")
	//    @ApiOperation(value="", notes="商城订单信息表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ZrkShoporder zrkShoporder) {
		zrkShoporderService.save(zrkShoporder);
		return Result.ok("添加成功！");
	}

	/**
	 *   添加
	 * @param zrkShoporder
	 * @return
	 */
	@AutoLog(value = "商城订单信息表-添加ERP")
	@ApiOperation(value="商城订单信息表-添加ERP", notes="商城订单信息表-添加ERP")
	@PostMapping(value = "/addERP")
	public Result<?> addERP(@RequestBody ZrkShoporder zrkShoporder) {
		zrkShoporder.setCreateTime(DateUtils.getDate());
		zrkShoporder.setOrderTime(DateUtils.getDate());
		//查询下单用户信息在ERP中对应的客户信息
		QueryWrapper<BasCustomerAddress> queryWrapper=new QueryWrapper<BasCustomerAddress>();
		queryWrapper.eq("phone_no", zrkShoporder.getCustomerMobile());//此处默认将客户公司法人手机号作为关联手机号
		BasCustomerAddress cus=basCustomerAddressService.getOne(queryWrapper.last("LIMIT 1"));//防止出现多条匹配，如果出现多条则随机取一条
		if(null!=cus) {
			zrkShoporder.setCustomerId(cus.getId());//设置客户编号
			QueryWrapper<ZrkUserCustomer> qw=new QueryWrapper<ZrkUserCustomer>();
			qw.eq("customer_id", cus.getId());
			//查询客户关联的业务员
			ZrkUserCustomer zrkUserCustomer=zrkUserCustomerService.getOne(qw);
			//查询是否为手动配置业务员
			if(null!=zrkUserCustomer) {
				//找到配置信息
				zrkShoporder.setSalsUser(zrkUserCustomer.getUserId());//设置业务员
			}
		}
		//    	else {
		//    		//如果未查询到客户则向客户表中添加客户信息
		//    		BasCustomer bc=new BasCustomer();
		//    		bc.setCorporatePhone(zrkShoporder.getCustomerMobile());
		//    		bc.setAddress(zrkShoporder.getCustomerAddress());
		//    		bc.setCashType("1");//默认设置现金账户
		//    		bc.setZhangqi(0);//设置账期为0
		//    		bc.setCreateBy("platform");
		//    		basCustomerService.save(bc);
		//    		QueryWrapper<ZrkUserCustomer> qw=new QueryWrapper<ZrkUserCustomer>();
		//    		qw.eq("customer_id", bc.getId());
		//    		//查询客户关联的业务员
		//    		ZrkUserCustomer zrkUserCustomer=zrkUserCustomerService.getOne(qw);
		//    		//查询是否为手动配置业务员
		//    		if(null!=zrkUserCustomer) {
		//    			//找到配置信息
		//    			zrkShoporder.setSalsUser(zrkUserCustomer.getUserId());//设置业务员
		//    		}
		//    	}
		zrkShoporderService.save(zrkShoporder);
		return Result.ok("添加成功！");
	}

	@AutoLog(value = "商城订单信息表-支付成功更新订单状态")
	@ApiOperation(value="商城订单信息表-支付成功更新订单状态", notes="商城订单信息表-支付成功更新订单状态")
	@PostMapping(value = "/updateERP")
	public Result<?> updateERP(@RequestBody ZrkShoporder zrkShoporder) {
		//此时zrkShoporder中只存储了一个shoporder
		System.err.println(zrkShoporder);
		QueryWrapper<ZrkShoporder> qw=new QueryWrapper<ZrkShoporder>();
		qw.eq("order_code", zrkShoporder.getShopOrder());
		//按道理讲，你应该只能查到一条记录
		ZrkShoporder zso=zrkShoporderService.getOne(qw.last("LIMIT 1"));
		if(null!=zso) {
			if(zrkShoporder.getOrderStatus().equals("")) {
				zso.setOrderStatus("2");//将订单状态设置为商城支付后获取的状态
			}else {
				zso.setOrderStatus(zrkShoporder.getOrderStatus());
			}
			zrkShoporderService.updateById(zso);
		}else {
			Result.error("未找到对应数据");
		}
		return Result.ok("更新成功");
	}

	/**
	 *  更新生产信息
	 * @param zrkShoporder
	 * @return
	 */
	@AutoLog(value = "更新生产信息")
	@ApiOperation(value="更新生产信息", notes="更新生产信息")
	@PostMapping(value = "/updateProduceInfo")
	public Result<?> updateProduceInfo(@RequestBody ZrkShoporder zrkShoporder) {
		//根据选中id查询销售订单信息
		ZrkShoporder zso=zrkShoporderService.getById(zrkShoporder.getId());
		//查询销售订单所需产品信息
		QueryWrapper<ZrkOrderProduct> qw=new QueryWrapper<ZrkOrderProduct>();
		qw.eq("order_no", zso.getOrderCode());
		List<ZrkOrderProduct> zspList=zrkOrderProductService.list(qw);
		//根据zso的id查询工单，如果有则判断工单状态，当工单状态为已完成时查询入库信息填充生产数量
		QueryWrapper<ZzShoporder> queryWrapper=new QueryWrapper<ZzShoporder>();
		queryWrapper.eq("order_no", zso.getId());
		List<ZzShoporder> zsList=zzShoporderService.list(queryWrapper);//工单信息
		Map<String,Object> map=new HashMap<String,Object>();
		String unitName="平方";
		if(null!=zsList&&zsList.size()>0) {
			for(ZzShoporder zs:zsList) {
				//生产完成
				if(zs.getWoStatus()==4) {
					//查询入库信息
					QueryWrapper<StkIoBill> qwIB=new QueryWrapper<StkIoBill>();
					qwIB.eq("source_no", zs.getWoPartcode());//原单号为工单号
					qwIB.and(wrapper->wrapper.in("stock_io_type", "1991","1992","1993"));
					List<StkIoBill> sibList=stkIoBillService.list(qwIB);
					//判断是否存在入库信息，有则填充产品生成信息
					if(null!=sibList&&sibList.size()>0) {
						for(StkIoBill sib:sibList) {
							QueryWrapper<StkIoBillEntry> sibeWrapper=new QueryWrapper<StkIoBillEntry>();
							sibeWrapper.eq("mid", sib.getId());
							//查询入库物料信息
							List<StkIoBillEntry> sibeList=stkIoBillEntryService.list(sibeWrapper);
							if(null!=sibeList&&sibeList.size()>0) {
								for(StkIoBillEntry sibe:sibeList) {
									BasMaterial bs=basMaterialService.getById(sibe.getMaterialId());
									for(StkIoBillEntry sibe2:sibeList) {
										if(sibe2.getWidth().compareTo(sibe.getWidth())==0&&sibe2.getLength().compareTo(sibe.getLength())==0) {
											//map有值
											if(null!=map&&map.size()>0) {
												String key=bs.getCategoryId()+"#"+sibe2.getLength().setScale(4)+"*"+sibe2.getWidth().setScale(4);
												Object spec=map.get(key);
												if(null!=spec&&!spec.equals("")) {
													//合并数量计算
													BigDecimal cu=new BigDecimal(spec.toString());
													BigDecimal tol=cu.add(sibe2.getQty());
													map.put(key, tol);
												}else {
													map.put(bs.getCategoryId()+"#"+sibe2.getLength().setScale(4)+"*"+sibe2.getWidth().setScale(4), sibe2.getQty());
												}
											}else {
												//map无值
												map.put(bs.getCategoryId()+"#"+sibe2.getLength().setScale(4)+"*"+sibe2.getWidth().setScale(4), sibe2.getQty());
											}
										}
									}
								}
							}
						}
					}
				}
			}
			//按照销售订单返回生产信息
			if(null!=zspList&&zspList.size()>0) {
				for(ZrkOrderProduct zop:zspList) {
					BigDecimal productCount=BigDecimal.ZERO;
					BasMaterial bss=basMaterialService.getById(zop.getMaterialId());
					if(null!=map&&map.size()>0) {
						for(Map.Entry<String, Object> entry : map.entrySet()){
							String mapKey = entry.getKey();
							Object mapValue = entry.getValue();
							String [] tm=mapKey.split("#");
							productCount=productCount.add(new BigDecimal(mapValue.toString()));
							if(bss.getCategoryId().equals(tm[0])) {
								String produceInfo;
								try {
									produceInfo = zop.getProduceInfo();
									if(null!=produceInfo&&!produceInfo.equals("")) {
										zop.setProduceInfo(produceInfo+"||"+tm[1]+"*"+mapValue);
									}else {
										zop.setProduceInfo(tm[1]+"*"+mapValue);
									}
								} catch (Exception e) {
									//相同分类下的物料
									zop.setProduceInfo(tm[1]+"*"+mapValue);
								}
							}
						}
						zop.setProductCount(productCount);//生产数量
						zrkOrderProductService.updateById(zop);//更新生产信息
					}
				}
			}
		}else {
			return Result.error("未找到任务工单");
		}
		return Result.ok("更新生产信息成功，如果生产工单没有完成则您不会看到任何数据更新!");
	}

	/**
	 *  生成车间任务单
	 * @param createZzOrderVO
	 * @return
	 */
	@AutoLog(value = "生成车间任务订单")
	@ApiOperation(value="生成车间任务订单", notes="生成车间任务订单")
	@PostMapping(value = "/createZzOrder")
	public Result<?> createZzOrder(@RequestBody CreateZzOrderVO createZzOrderVO) {
		//根据选中id查询销售订单信息
        try {
            return zrkShoporderService.createZzOrder(createZzOrderVO);
        } catch (RuntimeException e) {
        	e.printStackTrace();
            if(StringUtils.isBlank(e.getMessage())){
                e.printStackTrace();
                return Result.error("生成任务单失败，请联系管理员");
            }
            return Result.error(e.getMessage());
        }

    }


	/**
	 *  编辑
	 * @param zrkShoporder
	 * @return
	 */
	@AutoLog(value = "商城订单信息表-编辑")
	@ApiOperation(value="商城订单信息表-编辑", notes="商城订单信息表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ZrkShoporder zrkShoporder) {
		//编辑时判断是否修改了订单金额
		ZrkShoporder zso=zrkShoporderService.getById(zrkShoporder.getId());//查询数据库原有数据
		//判断是否修改了订单金额
		if(zso.getOrderMoney().compareTo(zrkShoporder.getOrderMoney())!=0) {
			//确认修改了订单金额,调用商城接口修改对应订单金额
			JSONObject jsonObject=new JSONObject();
			jsonObject.put("id", zrkShoporder.getShopOrder());
			jsonObject.put("price", zrkShoporder.getOrderMoney());
			jsonObject.put("reason", "ERP生产订单不满足订单要求，修改订单价格");
			jsonObject.put("shop_order", zrkShoporder.getShopOrder());
			RestUtil.get(ConstantMall.UPDATE_ORDER_PRICE, jsonObject);
		}
		if(!zrkShoporder.getOrderStatus().equals(zso.getOrderStatus())) {
			//确认修改了订单状态,调用商城接口修改对应订单状态
			JSONObject jsonObject=new JSONObject();
			jsonObject.put("id", zrkShoporder.getShopOrder());
			jsonObject.put("status", zrkShoporder.getOrderStatus());
			RestUtil.get(ConstantMall.UPDATE_ORDER_STATUS, jsonObject);
		}
		zrkShoporderService.updateById(zrkShoporder);
		return Result.ok("编辑成功,如果修改了订单价格请与客户协商好!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商城订单信息表-通过id删除")
	@ApiOperation(value="商城订单信息表-通过id删除", notes="商城订单信息表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		zrkShoporderService.delMain(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "商城订单信息表-批量删除")
	@ApiOperation(value="商城订单信息表-批量删除", notes="商城订单信息表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.zrkShoporderService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 导出
	 * @return
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, ZrkShoporder zrkShoporder) {
		return super.exportXls(request, zrkShoporder, ZrkShoporder.class, "商城订单信息表");
	}

	/**
	 * 导入
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, ZrkShoporder.class);
	}
	/*---------------------------------主表处理-end-------------------------------------*/


	/*--------------------------------子表处理-商城订单产品明细表-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "商城订单产品明细表-通过主表ID查询")
	@ApiOperation(value="商城订单产品明细表-通过主表ID查询", notes="商城订单产品明细表-通过主表ID查询")
	@GetMapping(value = "/listZrkOrderProductByMainId")
	public Result<?> listZrkOrderProductByMainId(ZrkOrderProduct zrkOrderProduct,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			HttpServletRequest req) {
		//查询主表数据
		ZrkShoporder zso=zrkShoporderService.getById(zrkOrderProduct.getOrderNo());
		QueryWrapper<ZrkOrderProduct> queryWrapper = new QueryWrapper<ZrkOrderProduct>();
		queryWrapper.eq("order_id", zso.getId());
		Page<ZrkOrderProduct> page = new Page<ZrkOrderProduct>(pageNo, pageSize);
		IPage<ZrkOrderProduct> pageList = zrkOrderProductService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "商城订单产品明细表-通过主表ID查询字典")
	@ApiOperation(value="商城订单产品明细表-通过主表ID查询字典", notes="商城订单产品明细表-通过主表ID查询字典")
	@GetMapping(value = "/listZrkOrderProductDetailsByMainId")
	public Result<?> listZrkOrderProductDetailsByMainId(ZrkOrderProduct zrkOrderProduct,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			HttpServletRequest req) {
		List<ZzShoporder> dictList=new ArrayList<ZzShoporder>();
		LambdaQueryWrapper<ZrkShoporder> query = new LambdaQueryWrapper<>();
		query.eq(ZrkShoporder::getId, zrkOrderProduct.getOrderNo());
		ZrkShoporder zrkShoporder = zrkShoporderService.getOne(query);
		Map<String,Object> columnMap=new HashMap<String,Object>();
		columnMap.put("order_no", zrkShoporder.getOrderCode());
		Collection<ZrkOrderProduct> list=zrkOrderProductService.listByMap(columnMap);
		if(null!=list&&list.size()>0) {
			Iterator<ZrkOrderProduct> iterator=list.iterator();
			while(iterator.hasNext()) {
				ZrkOrderProduct zop=iterator.next();
				//根据product_name记录的material_id查询产品信息
				BasMaterial basMaterial=basMaterialService.getById(zop.getMaterialId());
				//        		Dict dict=new Dict();
				//        		dict.setValue(zrkOrderProduct.getOrderNo());//value存储id
				//        		dict.setText(basMaterial.getName());//text存储产品名称
				//        		dictList.add(dict);
				ZzShoporder zzShoporder = new ZzShoporder();
				zzShoporder.setWoPartname(basMaterial.getId());
				zzShoporder.setSpecs(zop.getProductSpecs());
				if(null != zop.getProductCount()) {
					zzShoporder.setWoQuantity(zop.getProductCount().intValue());
				}
				zzShoporder.setPaperSupplier(zop.getDzId());
				zzShoporder.setGlueSupplier(zop.getJsId());
				zzShoporder.setFacialSupplier(zop.getMzId());
				dictList.add(zzShoporder);
			}
		}
		return Result.ok(dictList);
	}

	/**
	 * 添加
	 * @param zrkOrderProduct
	 * @return
	 */
	@AutoLog(value = "商城订单产品明细表-添加")
	@ApiOperation(value="商城订单产品明细表-添加", notes="商城订单产品明细表-添加")
	@PostMapping(value = "/addZrkOrderProduct")
	public Result<?> addZrkOrderProduct(@RequestBody ZrkOrderProduct zrkOrderProduct) {
		zrkOrderProductService.save(zrkOrderProduct);
		return Result.ok("添加成功！");
	}

	/**
	 * 添加
	 * @param zrkOrderProduct
	 * @return
	 */
	@AutoLog(value = "商城订单ERP产品明细表-添加")
	@ApiOperation(value="商城订单ERP产品明细表-添加", notes="商城订单ERP产品明细表-添加")
	@PostMapping(value = "/addZrkERPOrderProduct")
	public Result<?> addZrkERPOrderProduct(@RequestBody ZrkOrderProduct zrkOrderProduct) {
		//将商城中该商品的计量单位转换为ERP中的计量单位ID
		String unitName=zrkOrderProduct.getUnitId();
		try {
			if(null!=unitName&&!unitName.equals("")) {
				String [] tmp=unitName.split("\\|");
				if(null!=tmp&&tmp.length>0) {
					String [] tm=tmp[0].split(":");
					if(null!=tm&&tm.length>0) {
						//查询erp中该计量单位的id
						QueryWrapper<BasMeasureUnit> queryWrapper=new QueryWrapper<BasMeasureUnit>();
						queryWrapper.like("name", tm[1]);
						List<BasMeasureUnit> bmuList=basMeasureUnitService.list(queryWrapper);
						if(null!=bmuList&&bmuList.size()>0) {
							BasMeasureUnit bmu=bmuList.get(0);
							zrkOrderProduct.setUnitId(bmu.getId());
						}
					}
				}
			}

			//处理底纸、面纸、胶水的添加
			if(!zrkOrderProduct.getDzId().equals("")) {
				QueryWrapper<BasSupplier> qw=new QueryWrapper<BasSupplier>();
				qw.like("name", zrkOrderProduct.getDzId());
				BasSupplier bs=basSupplierService.getOne(qw.last("LIMIT 1"));
				if(null!=bs) {
					zrkOrderProduct.setDzId(bs.getId());
				}
			}
			if(!zrkOrderProduct.getMzId().equals("")) {
				QueryWrapper<BasSupplier> qw=new QueryWrapper<BasSupplier>();
				qw.like("name", zrkOrderProduct.getMzId());
				BasSupplier bs=basSupplierService.getOne(qw.last("LIMIT 1"));
				if(null!=bs) {
					zrkOrderProduct.setMzId(bs.getId());
				}
			}
			if(!zrkOrderProduct.getJsId().equals("")) {
				QueryWrapper<BasSupplier> qw=new QueryWrapper<BasSupplier>();
				qw.like("name", zrkOrderProduct.getJsId());
				BasSupplier bs=basSupplierService.getOne(qw.last("LIMIT 1"));
				if(null!=bs) {
					zrkOrderProduct.setJsId(bs.getId());
				}
			}
		} catch (Exception e) {
		}
		boolean flag=zrkOrderProductService.save(zrkOrderProduct);
		if(flag) {
			//重新查询一遍
			ZrkOrderProduct zop=zrkOrderProductService.getById(zrkOrderProduct.getId());
			//更新实时库存
			BigDecimal stock=stkInventoryService.getCPQtyByMaterialId(zop.getMaterialId());
			zop.setStock(stock.setScale(4,BigDecimal.ROUND_DOWN));
			zrkOrderProductService.updateById(zop);//此处找到了实时库存直接更新一下
			//更新原材料库存,查询产品配方
			BasMaterial bm=basMaterialService.getById(zop.getMaterialId());
			String materialStock="";
			if(null!=bm) {
				QueryWrapper<BasProductFormula> bpfQw=new QueryWrapper<BasProductFormula>();
				bpfQw.eq("pfid", bm.getCategoryId());
				BasProductFormula bpf=basProductFormulaService.getOne(bpfQw);
				if(null!=bpf) {
					QueryWrapper<BasPfMaterial> bmfQw=new QueryWrapper<BasPfMaterial>();
					bmfQw.eq("pfid", bpf.getId());
					List<BasPfMaterial> bpmList=basPfMaterialService.list(bmfQw);
					//遍历配方，查询原材料库存
					if(null!=bpmList&&bpmList.size()>0) {
						for(BasPfMaterial bpm:bpmList) {
							//查询该原材料的库存
							BigDecimal mt=stkInventoryService.getBCPQtyByCategoryId(bpm.getPfName());
							BasMaterialCategory mc=basMaterialCategoryService.getById(bpm.getPfid());
							if(materialStock.equals("")) {
								if(mc!=null) {
									materialStock="原材料："+mc.getName()+"的实时库存为："+mt;
								}else {
									return Result.error("未找到物料分类");
								}
							}else {
								if(mc!=null) {
									materialStock+="||"+"原材料："+mc.getName()+"的实时库存为："+mt;
								}else {
									return Result.error("未找到物料分类");
								}
							}
						}
					}else {
						return Result.error("产品配方详情查找失败");
					}
					zop.setMaterialStock(materialStock);
					zrkOrderProductService.updateById(zop);
				}else {
					return Result.error("产品配方查找失败");
				}
			}else {
				return Result.error("未查询到该物料信息");
			}
		}
		return Result.ok("添加成功！");
	}

	/**
	 * 编辑
	 * @param zrkOrderProduct
	 * @return
	 */
	@AutoLog(value = "商城订单产品明细表-编辑")
	@ApiOperation(value="商城订单产品明细表-编辑", notes="商城订单产品明细表-编辑")
	@PutMapping(value = "/editZrkOrderProduct")
	public Result<?> editZrkOrderProduct(@RequestBody ZrkOrderProduct zrkOrderProduct) {
		//判断是否修改了数量,修改数量后会自动同步商城订单商品数量
		ZrkOrderProduct zop=zrkOrderProductService.getById(zrkOrderProduct.getId());//查询原有数据
		//判断是否修改了数量
		if(zop.getProductCount()!=zrkOrderProduct.getProductCount()) {
			//确认修改了数量，同步商城订单sku数量
			JSONObject jsonObject=new JSONObject();
			jsonObject.put("id", zrkOrderProduct.getOmsOrderId());
			jsonObject.put("num", zrkOrderProduct.getProductCount());
			jsonObject.put("skuId", zrkOrderProduct.getOmsSkuId());
			RestUtil.get(ConstantMall.UPDSTE_OMSORDER_SKU_NUM,jsonObject);
		}
		//重新设置orderNo，确认与主表的关联关系
		zrkOrderProduct.setOrderNo(zop.getOrderNo());
		zrkOrderProductService.updateById(zrkOrderProduct);
		return Result.ok("编辑成功，如果修改了商品数量请通知客户!");
	}

	/**
	 * 编辑
	 * @param zrkOrderProduct
	 * @return
	 */
	//	@AutoLog(value = "商城订单产品明细表-编辑")
	//	@ApiOperation(value="商城订单产品明细表-编辑", notes="商城订单产品明细表-编辑")
	//	@PutMapping(value = "/editZrkOrderProduct2")
	//	public Result<?> editZrkOrderProduct2(@RequestBody ZrkOrderProduct zrkOrderProduct) {
	//		//判断是否修改了数量,修改数量后会自动同步商城订单商品数量
	//		ZrkOrderProduct zop=zrkOrderProductService.getById(zrkOrderProduct.getId());//查询原有数据
	//		//判断是否修改了数量
	//		if(zop.getProductCount()!=zrkOrderProduct.getProductCount()) {
	//			//确认修改了数量，同步商城订单sku数量
	//			JSONObject jsonObject=new JSONObject();
	//			jsonObject.put("id", zrkOrderProduct.getOmsOrderId());
	//			jsonObject.put("num", zrkOrderProduct.getProductCount());
	//			jsonObject.put("skuId", zrkOrderProduct.getOmsSkuId());
	//			RestUtil.get(ConstantMall.UPDSTE_OMSORDER_SKU_NUM,jsonObject);
	//		}
	//		zrkOrderProductService.updateById(zrkOrderProduct);
	//		return Result.ok("编辑成功，如果修改了商品数量请通知客户!");
	//	}


	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商城订单产品明细表-通过id删除")
	@ApiOperation(value="商城订单产品明细表-通过id删除", notes="商城订单产品明细表-通过id删除")
	@DeleteMapping(value = "/deleteZrkOrderProduct")
	public Result<?> deleteZrkOrderProduct(@RequestParam(name="id",required=true) String id) {
		zrkOrderProductService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "商城订单产品明细表-批量删除")
	@ApiOperation(value="商城订单产品明细表-批量删除", notes="商城订单产品明细表-批量删除")
	@DeleteMapping(value = "/deleteBatchZrkOrderProduct")
	public Result<?> deleteBatchZrkOrderProduct(@RequestParam(name="ids",required=true) String ids) {
		this.zrkOrderProductService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 导出
	 * @return
	 */
	@RequestMapping(value = "/exportZrkOrderProduct")
	public ModelAndView exportZrkOrderProduct(HttpServletRequest request, ZrkOrderProduct zrkOrderProduct) {
		// Step.1 组装查询条件
		QueryWrapper<ZrkOrderProduct> queryWrapper = QueryGenerator.initQueryWrapper(zrkOrderProduct, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// Step.2 获取导出数据
		List<ZrkOrderProduct> pageList = zrkOrderProductService.list(queryWrapper);
		List<ZrkOrderProduct> exportList = null;

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		} else {
			exportList = pageList;
		}

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "商城订单产品明细表"); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, ZrkOrderProduct.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商城订单产品明细表报表", "导出人:" + sysUser.getRealname(), "商城订单产品明细表"));
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

	/**
	 * 导入
	 * @return
	 */
	@RequestMapping(value = "/importZrkOrderProduct/{mainId}")
	public Result<?> importZrkOrderProduct(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ZrkOrderProduct> list = ExcelImportUtil.importExcel(file.getInputStream(), ZrkOrderProduct.class, params);
				for (ZrkOrderProduct temp : list) {
					temp.setOrderNo(mainId);
				}
				long start = System.currentTimeMillis();
				zrkOrderProductService.saveBatch(list);
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/*--------------------------------子表处理-商城订单产品明细表-end----------------------------------------------*/


	@AutoLog(value = "获取订单编号")
	@ApiOperation(value="获取订单编号", notes="获取订单编号")
	@PostMapping("/getErpOrderNo")
	public Result<?> getErpOrderNo(){
		String no = this.iSysBaseAPI.getNoByCode("shop_order_erp_no");
		return Result.ok(no);
	}

	@GetMapping("/getByCustomAndCategory")
	public Result<?> getByCustomAndCategory(String customId, String categoryId){
	    if(StringUtils.isBlank(customId)){
            return Result.error("未获取到客户信息");
        }
	    if(StringUtils.isBlank(categoryId)){
            return Result.error("未获取到物料分类信息");
        }
		ZrkOrderProduct latestByCustom = this.zrkOrderProductService.getLatestByCustom(customId, categoryId);
		if(null == latestByCustom) {
			return Result.error("未找到价格");
		} else {
			return Result.ok(latestByCustom);
		}
	}

	/**
	 * 代下单或修改
	 *
	 * @param orderVo
	 * @return
	 */
	@PostMapping("/addOrder")
	public Result<?> addOrder(@RequestBody OrderVO orderVo){
		return this.zrkShoporderService.addOrder(orderVo);
	}
	
	/**
	 * 直接添加或修改销售订单产品明细
	 * @param orderProductVo
	 * @return
	 */
	@PostMapping("/operationOrderProduct")
	public Result<?> operationOrderProduct(@RequestBody OrderProductVO orderProductVo){
		return this.zrkOrderProductService.addOrderProduct(orderProductVo);
	}
	
	/**
	 * 直接删除销售订单产品明细
	 * @param id
	 * @return
	 */
	@PostMapping("/deleteOrderProduct")
	public Result<?> deleteOrderProduct(@RequestParam String id){
		return this.zrkOrderProductService.deleteOrderProduct(id);
	}
	
	@GetMapping("/getChild")
	public Result<?> getChild(String id){
		return this.zrkOrderProductService.getChild(id);
	}

	/**
	 * 撤单
	 * @param id
	 * @return
	 */
	@GetMapping("/recallOrder")
	public Result<?> recallOrder(String id){
		return zrkShoporderService.recallOrder(id);

	}
	
	/**
	 * 销售订单作废
	 * @param id
	 * @return
	 */
	@GetMapping("/delOrder")
	public Result<?> delOrder(String id){
		return zrkShoporderService.delOrder(id);

	}
	
	/**
	 * 新增调整单价功能
	 * @param orderProductVo
	 * @return
	 */
	@AutoLog(value = "新增调整单价功能")
	@ApiOperation(value="新增调整单价功能", notes="新增调整单价功能")
	@PutMapping("/updatePrice")
	public Result<?> updatePrice(@RequestBody ZrkOrderProduct orderProductVo){
		zrkOrderProductService.changePrice(orderProductVo);
		return Result.ok("调整单价成功");

	}

	/**
	 * 新增客户购买过哪些物料，价格及下单日期菜单
	 * @param zrkShoporder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "新增客户购买过哪些物料，价格及下单日期菜单")
	@ApiOperation(value="新增客户购买过哪些物料，价格及下单日期菜单", notes="新增客户购买过哪些物料，价格及下单日期菜单")
	@GetMapping(value = "/queryList")
	public Result<?> queryList(ZrkShoporder zrkShoporder,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		String customerName = req.getParameter("customerName");
		Page<ZrkShopCustomerDTO> page = new Page<ZrkShopCustomerDTO>(pageNo, pageSize);
		Page<ZrkShopCustomerDTO> pageList = zrkShoporderService.getCustomerAndProduct(page,customerName);
		return Result.ok(pageList);
	}
	
	/**
	 *新增销售统计菜单--选择人员之后展示：物料名，数量，规格，单价，总金额
	 * @param zrkOrderProduct
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "新增销售统计菜单--选择人员之后展示：物料名，数量，规格，单价，总金额")
	@ApiOperation(value="新增销售统计菜单--选择人员之后展示：产品名称 productName，产品数量productCount，产品规格productSpecs，单价unitPrice，总金额 totalPrice", notes="新增销售统计菜单--选择人员之后展示：物料名，数量，规格，单价，总金额")
	@GetMapping(value = "/salesStatistics")
	public Result<?> salesStatistics(ZrkOrderProduct zrkOrderProduct,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		String createBy = req.getParameter("createBy");
		//查询主表数据
		QueryWrapper<ZrkShoporder> query = new QueryWrapper<ZrkShoporder>();
		query.eq("create_by", createBy);
		List<ZrkShoporder> zrkShoporderList = zrkShoporderService.list(query);
		List<String> idsList = Lists.newArrayList();
		if(zrkShoporderList!=null&&zrkShoporderList.size()>0) {
			for(ZrkShoporder zrkShoporder:zrkShoporderList) {
				idsList.add(zrkShoporder.getId());
			}
		}
		QueryWrapper<ZrkOrderProduct> queryWrapper = new QueryWrapper<ZrkOrderProduct>();
		queryWrapper.in("order_id", idsList);
		Page<ZrkOrderProduct> page = new Page<ZrkOrderProduct>(pageNo, pageSize);
		IPage<ZrkOrderProduct> pageList = zrkOrderProductService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 * 销售订单--合计某一个客户总平方，总金额
	 * @param zrkShoporder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "销售订单--合计某一个客户总平方，总金额")
	@ApiOperation(value="销售订单--合计某一个客户总平方，总金额", notes="销售订单--合计某一个客户总平方，总金额")
	@GetMapping(value = "/queryTotalList")
	public Result<?> queryTotalList(ZrkShoporder zrkShoporder,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		String orderTimeBegin = req.getParameter("orderTime_begin");
		String orderTimeEnd = req.getParameter("orderTime_end");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		if(oConvertUtils.isEmpty(orderTimeEnd)) {
			orderTimeEnd = format.format(c.getTime());
		}
		if(oConvertUtils.isEmpty(orderTimeBegin)) {
	        c.add(Calendar.MONTH, -1);
	        Date m = c.getTime();
			orderTimeBegin = format.format(m);
		}
//		if(oConvertUtils.isEmpty(customerName)) {
//			return Result.error("未知客户");
//		}
		String customerName = req.getParameter("customerName");
		Page<ZrkShopTotalDTO> page = new Page<ZrkShopTotalDTO>(pageNo, pageSize);
		Page<ZrkShopTotalDTO> pageList = zrkShoporderService.getShopTotal(page,customerName,orderTimeBegin,orderTimeEnd);
		return Result.ok(pageList);
	}
	
	/**
	 * 代下单--新增下单人销量统计菜单
	 * @param zrkShoporder
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 * @throws ParseException 
	 */
	@AutoLog(value = "代下单--新增下单人销量统计菜单")
	@ApiOperation(value="代下单--新增下单人销量统计菜单", notes="代下单--新增下单人销量统计菜单")
	@GetMapping(value = "/querySalesVolumeByUser")
	public Result<?> querySalesVolumeByUser(ZrkShoporder zrkShoporder,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) throws ParseException {
		String orderTimeBegin = req.getParameter("orderTime_begin");
		String orderTimeEnd = req.getParameter("orderTime_end");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		if(oConvertUtils.isEmpty(orderTimeEnd)) {
			orderTimeEnd = format.format(c.getTime());
		}else {
			DateUtil.parseDate(orderTimeEnd);
			long mills = DateUtils.getMillis(DateUtil.parseDate(orderTimeEnd));
			mills = mills + 24*60*60*1000;
			orderTimeEnd = format.format(DateUtils.getDate(mills));
		}
		if(oConvertUtils.isEmpty(orderTimeBegin)) {
			c.set(Calendar.HOUR_OF_DAY, 0);
			c.set(Calendar.MINUTE, 0);
			c.set(Calendar.SECOND, 0);
			c.set(Calendar.MILLISECOND, 0);
	        Date m = c.getTime();
			orderTimeBegin = format.format(m);
		}
		String users = req.getParameter("createBy");
		String[] createBy = null;
		if(oConvertUtils.isNotEmpty(users)) {
			createBy = users.split(",");
		}
		Page<ZrkOrderProductDTO> page = new Page<ZrkOrderProductDTO>(pageNo, pageSize);
		Page<ZrkOrderProductDTO> pageList = zrkShoporderService.querySalesVolumeByUser(page, createBy, orderTimeBegin, orderTimeEnd);
		return Result.ok(pageList);
	}
	
	@AutoLog(value = "产品购买记录-产品明细")
	@ApiOperation(value="产品购买记录-产品明细", notes="产品购买记录-产品明细")
	@GetMapping("/getOrderProduct")
	public Result<?> getOrderProduct(String orderProductId){
		Page<ZrkOrderProduct> page = new Page<ZrkOrderProduct>(1, 10);
		QueryWrapper<ZrkOrderProduct> queryWrapper = new QueryWrapper<ZrkOrderProduct>();
		queryWrapper.eq("id", orderProductId);
		IPage<ZrkOrderProduct> pageList = zrkOrderProductService.page(page, queryWrapper);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(pageList!=null && pageList.getSize()>0) {
			for(ZrkOrderProduct zrk:pageList.getRecords()) {
				zrk.setShopTime(sdf.format(zrk.getCreateTime()));
			}
		}
		return Result.ok(pageList);
	}
	
	
	@AutoLog(value = "销售单下单人更改")
	@ApiOperation(value="销售单下单人更改", notes="销售单下单人更改")
	@PutMapping(value = "/editCreateBy")
	public Result<?> editCreateBy(@RequestBody ZrkShoporder zrkShoporder) {
		zrkShoporderService.updateCreateBy(zrkShoporder);
		return Result.ok("销售单下单人更改成功");
	}

}
